package com.topwalk.step01;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

/**
 * 管道
 * 这里的示例代码使用的是基于字符的：
 *
 * @author tang
 * @since 2023/10/13
 */
@Slf4j
public class Demo5_5Pipe {

    static class ReaderThread implements Runnable {

        private final PipedReader reader;

        public ReaderThread(PipedReader reader) {
            this.reader = reader;
        }

        @Override
        public void run() {
            log.debug("this is reader");
            int receive;
            try {
                while ((receive = reader.read()) != -1) {
                    log.debug("{}", (char) receive);
                }
            } catch (IOException e) {
                log.error("", e);
            }
        }

    }
    
    static class WriterThread implements Runnable {
        
        private final PipedWriter writer;

        public WriterThread(PipedWriter writer) {
            this.writer = writer;
        }

        @Override
        public void run() {
            log.debug("this is writer");
            try {
                writer.write("test");
            } catch (IOException e) {
                log.error("", e);
            } finally {
                try {
                    writer.close();
                } catch (IOException e) {
                    log.error("", e);
                }
            }
        }
        
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        PipedWriter writer = new PipedWriter();
        PipedReader reader = new PipedReader();
        writer.connect(reader); // 这里注意一定要连接上，才能通信
        
        new Thread(new ReaderThread(reader)).start();
        Thread.sleep(0);
        new Thread(new WriterThread(writer)).start();
    }

}
